package com.yape.webCrawler.base;

import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @Author Hazuki
 * @Date 2025/5/23 上午9:24
 * @Version 1.0
 */
@Slf4j
public class CrawlerContext {
    private final String name;
    private final String logId;
    private final LocalDateTime startTime;
    private LocalDateTime endTime;
    private final DateTimeFormatter formatter;

    public CrawlerContext(String name) {
        this.name = name;
        this.logId = UUID.randomUUID().toString().substring(0, 8);
        this.startTime = LocalDateTime.now();
        this.formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    }

    public void printHeader(String url) {
        log.info("============爬虫任务信息============");
        log.info("日志ID: {}", logId);
        log.info("爬虫说明: {}", name);
        log.info("爬虫URL: {}", url);
        log.info("开始时间: {}", getFormattedStartTime());
    }

    public void complete(int dataCount) {
        this.endTime = LocalDateTime.now();
        log.info("============爬虫任务完成============");
        log.info("结束时间: {}", getFormattedEndTime());
        log.info("耗时: {}毫秒", java.time.Duration.between(startTime, endTime).toMillis());
        log.info("数据条数: {}", dataCount);
    }

    public String getLogId() {
        return logId;
    }

    public String getFormattedStartTime() {
        return startTime.format(formatter);
    }

    public String getFormattedEndTime() {
        return endTime != null ? endTime.format(formatter) : "";
    }

    public String getCurrentTime() {
        return LocalDateTime.now().format(formatter);
    }

    public String getName() {
        return name;
    }

    public long getDurationMillis() {
        if (endTime == null) {
            return java.time.Duration.between(startTime, LocalDateTime.now()).toMillis();
        }
        return java.time.Duration.between(startTime, endTime).toMillis();
    }
}